const { Projects,Admin } = require('../models/index')
const { pick } = require('../util/util')
const { Op } = require('sequelize');

//发布项目
function publishProject(params) {
  return new Promise((resolve, reject) => {
    const { admin_id, title, info, people_num, categorization, start_time, over_time } = params
    Projects.create({
      admin_id,
      title,
      info,
      people_num,
      categorization,
      start_time,
      over_time,
      status: 0
    }
    ).then(data => {
      resolve(data)
    }).catch(err => {
      reject(`查询管理员失败：${err.message}`)
      logError(`查询管理员失败：${err.message}`)
    })
  })
}

//根据用户id获取项目
function getProjectList(admin_id) {
  return new Promise((resolve, reject) => {
    Projects.findAll({
      where: {
        admin_id
      }
    }).then(data => {
      resolve(data)
    }).catch(err => {
      reject(`查询项目失败：${err.message}`)
      logError(`查询管理员失败：${err.message}`)
    })
  })
}

// 根据id修改项目
function updateProject(params) {
  return new Promise((resolve, reject) => {
    const { admin_id, project_id, title, info, people_num, categorization, start_time, over_time, status } = params
    Projects.findOne({
      where: {
        project_id
      }
    }).then(data => {
      if (data.admin_id !== admin_id) {
        reject('项目不属于该用户')
      } else {
        Projects.update(
          { title, info, people_num, categorization, start_time, over_time, status },
          {
            where: {
              project_id
            }
          }
        ).then(data => {
          resolve(data)
        }).catch(err => {
          reject(`修改项目失败：${err.message}`)
          logError(`查询管理员失败：${err.message}`)
        })
      }
    })
  })
}


//根据title模糊获取项目
function getProjectByTitle(params) {
  return new Promise((resolve, reject) => {
    const { title } = params;
    // 构建查询条件
    const query = title
      ? { where: { title: { [Op.like]: `%${title}%` } } }
      : {};

    Projects.findAll(query)
      .then(data => {
        resolve(data);
      })
      .catch(err => {
        const errorMessage = `查询项目失败：${err.message}`;
        reject(errorMessage);
        logError(errorMessage);
      });
  });
}

// 根据id获取项目详情
function getProjectById(params) {
  const { project_id } = params;
  return new Promise((resolve, reject) => {
    Projects.findOne({
      where: {
        project_id
      },
      include: [
        {
          model: Admin, // 关联的项目表
          as: 'adminInfo', // 使用别名
          attributes: ['name', 'avatar', 'sex', 'qq', 'phone_num'], // 选择要返回的字段
        }]
    }).then(data => {
      resolve(data)
    }).catch(err => {
      reject(`查询项目失败：${err.message}`)
      logError(errorMessage);
    });
  });
}








module.exports = {
  publishProject, getProjectList, updateProject, getProjectByTitle, getProjectById
}